package com.docker.upload;

import com.alibaba.fastjson.JSONObject;
import com.docker.core.mvc.service.BaseService;
import com.jfinal.kit.PathKit;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.upload.UploadFile;
import kit.docker.file.FileKit;

import java.io.File;

/**
 * @Author ldl
 * @Create 2020/10/21 021 17:03
 */
public class UploadService extends BaseService {

    public Record upload(UploadFile file, UploadBean uploadBean, String inUserId) {
        if (!UploadConstant.uploadCodeList.contains(uploadBean.getUpload_code())) {
            throwError("未知上传类型");
        }
        checkFile(file, uploadBean.getUpload_code());
        //保存文件并返回相对路径
        String uploadPath = buildPath(file, uploadBean, inUserId);
        return new Record().set("upload_path", uploadPath);
    }

    private String buildPath(UploadFile file, UploadBean uploadBean, String userId) {
        switch (uploadBean.getUpload_code()) {
            case UploadConstant.docker_ssl:
                return dockerSSLPath(file, uploadBean);
            default:
                break;
        }
        //生成文件名
        String fileName = generateFileName(FileKit.getExtName(file.getFileName()));
        //构建相对路径
        String relativePath = buildRelativePath(uploadBean.getUpload_code(), getUUID32(), uploadBean.getApp_id());
        //构建绝对路径
        String absolutePath = buildAbsolutePath(relativePath);
        // 转移文件存储路径并对文件重命名
        FileKit.renameTo(file.getFile(), absolutePath + fileName);
        return relativePath + fileName;
    }

    private String dockerSSLPath(UploadFile file, UploadBean uploadBean) {
        String dirName = getUUID32();
        if (StrKit.notBlank(uploadBean.getExtra_param())) {
            try {
                JSONObject extraParam = JSONObject.parseObject(uploadBean.getExtra_param());
                dirName = extraParam.getString("server_id");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        //构建相对路径
        String relativePath = buildRelativePath(uploadBean.getUpload_code(), dirName, uploadBean.getApp_id());
        //构建绝对路径
        String absolutePath = buildAbsolutePath(relativePath);
        File yFile = new File(absolutePath + file.getFileName());
        if (yFile.exists()) {
            FileKit.deleteFile(yFile);
        }
        // 转移文件存储路径并对文件重命名
        FileKit.renameTo(file.getFile(), absolutePath + file.getFileName());
        return absolutePath;
    }

    //获取绝对路径
    private String buildAbsolutePath(String relativePath) {
        String absolutePath = PathKit.getWebRootPath() + relativePath;
        File temp = new File(absolutePath);
        if (!temp.exists()) {
            temp.mkdirs();
        }
        return absolutePath;
    }

    //获取相对路径
    private String buildRelativePath(String uploadCode, String dirName, String appId) {
        return UploadConstant.pathMap.get(uploadCode) + File.separator + dirName + File.separator;
    }

    private String generateFileName(String extName) {
        return getUUID32() + "." + extName;
    }

    //校验文件有效性
    private void checkFile(UploadFile uf, String uploadCode) {
        if (!StrKit.notNull(uf) || !StrKit.notNull(uf.getFile())) {
            throwUploadError(uf, "上传文件为空");
        }
        // 文件名为空 或 文件后缀为空 或文件上传类型代码不存在 或 文件类型代码不符合要求
        if (StrKit.isBlank(uf.getFileName())
                || StrKit.isBlank(FileKit.getExtName(uf.getFileName()))) {
            throwUploadError(uf, "文件类型错误");
        }

        if (!UploadConstant.fileMap.containsKey(uploadCode)) {
            throwUploadError(uf, "不支持的上传类型");
        }
        if (!UploadConstant.fileMap.get(uploadCode).contains(FileKit.getExtName(uf.getFileName()))) {
            throwUploadError(uf, "文件类型不符合规范,支持的类型：" + UploadConstant.fileMap.get(uploadCode).toString());
        }
        if (uf.getFile().length() > UploadConstant.fileSize.get(uploadCode)) {
            int i = UploadConstant.fileSize.get("advertiser_img") / 1024 / 1024;
            if (i < 1) {
                i = UploadConstant.fileSize.get("advertiser_img") / 1024;
                throwUploadError(uf, "文件大小超出" + i + "K");
            }
            throwUploadError(uf, "文件大小超出" + i + "M");
        }
    }

}
